clc
close all
clear all

myimage = imread('343x.jpg');

imshow(myimage);
hold on

% select source control points
source = ginput(4);
plot(source([1:end 1], 1), source([1:end 1], 2), 'Color', [1 0 0]);


% select target control points
target = ginput(4);
plot(target([1:end 1], 1), target([1:end 1], 2), 'Color', [0 1 0]);


for i = 1:size(source, 1)
    plot([source(i, 1) target(i, 1)], [source(i, 2) target(i, 2)])
end

% compute mapping from target to source
W = thinPlateSpline(target, source);

% sample points in target space and warp them to source space
[X Y] = meshgrid(1:size(myimage, 1), 1:size(myimage, 2));
new_points = thinPlateWarp([Y(:) X(:)], target, W);

% interpolate colour in source image and store them in target image
newimage = zeros(size(myimage));
for i = 1:size(myimage, 3)
    newimage(:, :, i) = reshape(interp2(double(myimage(:, :, i))/255, new_points(:, 1), new_points(:, 2), 'bilinear*'), size(myimage, 2), size(myimage, 1))';
end

% show new image
figure
imshow(newimage)
